<template>
    <!--安全U盾登录-->
    <a-modal v-model="showUKeyAuth"  :width="840"
             title="UKey授权管理"
             :maskClosable="false"
             :destroyOnClose="true" @cancel="cancelAuthUKey">
        <a-form :form="form" class="modelSearch">
            <a-form-item label="用户登录名：" v-bind="formStyle">
                <a-input v-model="uKeyDevFrom.userName"  disabled />
            </a-form-item>
            <a-form-item label="用户姓名：" v-bind="formStyle">
                <a-input v-model="uKeyDevFrom.name"  disabled />
            </a-form-item>
            <a-form-item label="身份证号：" v-bind="formStyle">
                <a-input v-model="uKeyDevFrom.sfzjh"  disabled />
            </a-form-item>
            <a-form-item label="安全UKey：" v-bind="formStyle" :extra="uKeyDevFrom.serialNum === ''?nullMsg:''">
                <a-input v-model="uKeyDevFrom.serialNum" disabled />
            </a-form-item>
            <a-form-item label="PIN 码：" v-bind="formStyle" :extra="msg">
                <a-input type="password" v-model="uKeyDevFrom.pinCode"
                         :disabled="authCtlflag.loginBtnCtl"  @change="validePassword(uKeyDevFrom.pinCode,'msg')"/>
            </a-form-item>
            <!-- 登录页驱动下载处理 -->
            <div>
              <span v-if ='showLoadUrl' style="font-size: 16px;color: #419aff;cursor: pointer;float: right;margin-top: -20px;margin-right: 13px;"
                    @click="downLoadUkeyDevice()" >下载UKey实体鉴别客户端</span>
                <iframe id="ifile" style="display: none"></iframe>
            </div>
        </a-form>
        <div slot="footer">
            <a-button type="default" size="default" @click="cancelAuthUKey()">取消</a-button>
            <a-button type="primary" size="default" @click="loginNewDev()"
                      :disabled="authCtlflag.loginBtnCtl">授权
            </a-button>
        </div>
    </a-modal>
</template>
<script>
    const Base64 = require ('js-base64').Base64
    import * as State from '@/libs/baseStateConts'
    import { mapState, mapActions } from 'vuex'
    export default {
        name: 'init-ukey-auth',
        data () {
            /**
             * UKEY设备PIN码验证（6个数值型字符）
             */
            const validePinCode = ( rule, value, callback ) => {
                if (!value || value.trim ().length === 0) {
                    callback (new Error ('安全UKey登录密码不能为空'))
                } else if (value.trim ().length < 6 || value.trim ().length > 16) {
                    callback (new Error ('请输入6-16密码'))
                } else {
                    callback ()
                }
            }

            return {
                showUKeyAuth: false,
                form: this.$form.createForm(this),
                formStyle: {
                    labelCol: { span: 6 },
                    wrapperCol: { span: 17 }
                },
                //授权表单
                uKeyDevFrom: {
                    id: '',
                    userName: '',
                    password: '',
                    roleType: '',
                    name: '',
                    sfzjh: '',
                    serialNum: '',
                    pinCode: ''
                },

                isUKeyLogin: false,
                showLoadUrl: false,
                scanUKeyTimer: -1,
                //授权表单控制
                authCtlflag: {
                    loginBtnCtl: true,
                    authBtnCtl: true
                },
                options1: [
                    {
                        value: '1',
                        label: '系统管理员'
                    },
                    {
                        value: '2',
                        label: '普通操作员'
                    }
                ],
                timer: '',
                getUkeyCount: 0,
                isFirst: true,
                oldDeviceId: sessionStorage.getItem ('deviceId'),
                nullMsg: '',
                isProtectiveUser:false,
                isForm:'',
                msg:'',
            }
        },

        computed: {
            ...mapState ({
                qsBackData: state => state.common.qsBackData,
            }),
            ...mapState('global', {
                qsLibAll: state => state.qsLibAll
            }),
        },
        watch: {
            qsBackData:{
                handler(val){
                    if(this.showUKeyAuth) {
                        let optWeb = val.optWeb
                        if (optWeb === 6) {
                            this.qsLibAll.getPublicKeyFun(this.uKeyDevFrom.serialNum)
                        }else if (optWeb === 9) {
                            this.msg = val.message
                        }else if (optWeb === 7) {
                            this.qsLibAll.checkAuthUKey (this.uKeyDevFrom.serialNum,this.uKeyDevFrom.pinCode)
                        }else if (optWeb === 8) {
                            this.showLoadUrl = true
                        }else if (optWeb === 113) {
                            this.bindUserUkey(val.data)
                        }else if (optWeb === 1) {
                            if(val.data.length === 1){
                                this.uKeyDevFrom.serialNum = ''
                                this.uKeyDevFrom.pinCode = ''
                                this.nullMsg = '请插入需要授权的安全UKey'
                                this.authCtlflag.authBtnCtl = true
                                this.authCtlflag.loginBtnCtl = true
                            }else if(val.data.length === 2){
                                let target = val.data.filter(itm=>itm.device_id !== this.oldDeviceId)
                                this.uKeyDevFrom.serialNum =  target[0].device_id;
                                this.nullMsg = ''
                                this.authCtlflag.loginBtnCtl = false
                                this.authCtlflag.authBtnCtl = false
                            }else{
                                this.uKeyDevFrom.serialNum= ''
                                this.uKeyDevFrom.pinCode= ''
                                this.nullMsg = '存在多个安全UKey'
                                this.authCtlflag.authBtnCtl = true
                                this.authCtlflag.loginBtnCtl = true
                            }

                        }else if (optWeb === 4098) {
                            this.uKeyDevFrom.serialNum = ''
                            this.nullMsg =  val.message
                            this.uKeyDevFrom.pinCode= ''
                            this.msg = ''
                            this.authCtlflag.authBtnCtl = true
                            this.authCtlflag.loginBtnCtl = true
                        }
                    }
                },
                deep:true,
                immediate: false
            },
        },

        methods: {
            validePassword(value,type){
                this[type] = ''
                if (!value || value.trim ().length === 0) {
                    this[type] = '安全UKey登录密码不能为空'
                } else if (value.trim ().length < 6 || value.trim ().length > 16) {
                    this[type] = '请输入6-16位安全UKey登录密码'
                }
            },

            /**
             * 开启扫描UKey设备定时器
             */
            startScanTimer () {
                let _this = this
                _this.clearScanTimer ()
                //开启扫描外接密钥存储设备定时器
                _this.uKeyDevFrom.pinCode = ''

                _this.authCtlflag.loginBtnCtl = true
                _this.authCtlflag.authBtnCtl = true
                /*_this.timer = setInterval (function () {
                    _this.qsLibAll.getDeviceInfo()
                }, 1000 * 6)*/
            },

            /**
             * 关闭扫描UKey设备定时器
             */
            clearScanTimer () {
                let _this = this
                if (_this.timer !== null) {
                    clearInterval (_this.timer)
                    _this.timer = null
                }
            },

            /**
             * Function    : downLoadUkeyDevice
             * Description : 下载UKey认证登录驱动
             * a-input       : None
             * Return      : None
             */
            downLoadUkeyDevice () {
                document.getElementById ('ifile').src = State.downloadUKeyAuthTool
            },

            loginNewDev(){
                let _this = this
                if((_this.msg === '' || _this.msg === null) && _this.uKeyDevFrom.serialNum !== ''){
                    if(_this.uKeyDevFrom.pinCode === ''){
                        _this.msg = '请输入PIN码'
                        return
                    }
                    _this.msg = ''
                    _this.authCtlflag.authBtnCtl = true
                    _this.authCtlflag.loginBtnCtl = true
                    //_this.qsLibAll.checkAuthUKey (_this.uKeyDevFrom.serialNum,_this.uKeyDevFrom.pinCode)
                    _this.qsLibAll.setInitParams (_this.uKeyDevFrom.serialNum)
                }
            },
            /**
             * Function    : cancelAuthUKey
             * Description : 取消授权操作
             * a-input       : fromName 授权表单信息
             * Return      : None
             */
            cancelAuthUKey ( fromName ) {
                let _this = this

                _this.showUKeyAuth = false


                //清空表单信息
                _this.uKeyDevFrom={
                    id: '',
                    userName: '',
                    password: '',
                    roleType: '',
                    name: '',
                    sfzjh: '',
                    serialNum: '',
                    pinCode: ''
                }

                /**
                 * 初始化表单操作按钮状态
                 */
                _this.authCtlflag.authBtnCtl = true
                _this.authCtlflag.loginBtnCtl = true
                this.uKeyDevFrom.serialNum = ''
                _this.clearScanTimer ()
            },
            showUserModal (rowData,isFrom) {
                let _this = this
                this.isFrom = isFrom
                //表单初始化赋值
                _this.uKeyDevFrom = Object.assign({},_this.uKeyDevFrom, rowData);

                /**
                 * 是否是针对系统默认用户授权
                 */
                _this.isProtectiveUser = '1' === rowData.protective;

                //初始化页面按钮、可编辑表单输入框状态
                _this.authCtlflag.authBtnCtl =true;
                _this.authCtlflag.loginBtnCtl =true;
                _this.showUKeyAuth = true;
                _this.msg ='';
                _this.nullMsg ='';
                _this.showUKeyAuth ='';
                /*_this.startScanTimer();*/
                _this.showUKeyAuth = true
                _this.uKeyDevFrom.serialNum = ''
            },

            bindUserUkey(data) {
                let _this = this
                let prams = {
                    username:_this.uKeyDevFrom.userName,
                    deviceId:_this.uKeyDevFrom.serialNum,
                    publicKey:data
                }
                this.$post('api/sysuser/bindUserUkey',prams, 'auth').then(res => {
                    _this.authCtlflag.loginBtnCtl = false
                    _this.authCtlflag.authBtnCtl = false
                    if (res.code === 0) {
                        _this.showUKeyAuth = false
                        _this.$message.success (res.message)
                        _this.isFrom = ''
                        //关闭扫描外接UKey设备定时器
                        _this.clearScanTimer ()
                        //清空表单信息
                        _this.uKeyDevFrom={
                            id: '',
                            userName: '',
                            password: '',
                            roleType: '',
                            name: '',
                            sfzjh: '',
                            serialNum: '',
                            pinCode: ''
                        }
                        _this.$emit('init')
                    } else {
                        this.$confirm ({
                            title: `UKey已绑定`+res.data+`用户，确定重置吗？`,
                            onOk: () => {
                                _this.$post('api/sysuser/unbindUserUkey',{username:res.data}).then(ress => {
                                    if (ress.code === 0) {
                                        _this.qsLibAll.getPublicKeyFun(this.uKeyDevFrom.serialNum)
                                    } else {
                                        _this.$message.error(ress.message)
                                    }
                                })
                            },
                            onCancel: () => {
                                _this.$message.warning('请重新更换UKey')
                            }
                        })
                    }
                })
            },
        },
        destroyed () {
            //关闭扫描外接UKey设备定时器
            this.clearScanTimer ()
        }
    }
</script>
<style lang="less" scoped>

</style>
